package de.koller.million.grid.engine;

import de.koller.million.grid.engine.player.Player;
import de.koller.million.grid.GNode;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

public class PlayerContainer extends GNode {
	
	private final Set<Player> players = new HashSet<>();
	private int playerInGrpG = 0;
	
	@Override
	protected void init() {
		super.init();
	
		String[] ps = new File( "./grid/player/" ).list();
		if( ps != null )
			for( String p : ps )
				if( p.startsWith( "p_" ) ) {
					String o = p.replaceAll( "p_", "" );
					loadPlayer( o );
				}
		
		grpChanged();
	}

	@Override
	protected void release() {
		super.release();
		
		for( Player p : players )
			p.save();
	}

	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		for( Player p : players )
			p.step( elapsedTime );
	}
	
	public Player loadPlayer( String name ) {
		Player p = new Player( name, groot.engine );
		players.add( p );
		return p;
	}
	
	public Player createPlayer( String name ) {
		Player p = new Player( name, groot.engine );
		players.add( p );
		
		return p;
	}
	
	public boolean isNameAvailable( String name ) {
		for( Player p : players )
			if( name.equals( p.name ) )
				return false;
		return true;
	}
	
	public int getPlayerNumber() {
		return players.size();
	}

	public Set<Player> getPlayers() {
		return players;
	}

	public void grpChanged() {
		int c = 0;
		for( Player p : players )
			if( p.getGrp().contains( (int)'G' ) )
				c++;
		
		playerInGrpG = c;
	}

	public int getPlayerInGrpG() {
		return playerInGrpG;
	}
	
}
